package com.boyi.shared.util;


import org.apache.commons.lang3.StringUtils;

/**
 * @author tingwen
 * @date 2018年07月11日  下午 02:27
 */
public class CRC16 {
    private CRC16() {
    }

    // 传入四个个十六进制的十进制数,传出六个十六进制的十进制数,后两个就是crc16校验的低八位和高八位
    public static int[] getCrc16(int[] data) {
        int[] temdata = new int[data.length + 2];
        // unsigned char alen = *aStr – 2; //CRC16只计算前两部分
        int xda, xdapoly;
        int i, j, xdabit;
        xda = 0xFFFF;
        xdapoly = 0xA001; // (X**16 + X**15 + X**2 + 1)
        for (i = 0; i < data.length; i++) {
            xda ^= data[i];
            for (j = 0; j < 8; j++) {
                xdabit = (int) (xda & 0x01);
                xda >>= 1;
                if (xdabit == 1) {
                    xda ^= xdapoly;
                }
            }
        }
        System.arraycopy(data, 0, temdata, 0, data.length);
        temdata[temdata.length - 2] = (int) (xda & 0xFF);
        temdata[temdata.length - 1] = (int) (xda >> 8);
        return temdata;
    }

    public static byte[] getCrc16(String directive) {
        String[] codes = StringUtils.split(directive, " ");
        int[] a = new int[codes.length];
        for (int i = 0, k = codes.length; i < k; i++) {
            a[i] = Integer.valueOf(codes[i], 16);
        }
        int[] intsCRC = CRC16.getCrc16(a);

        byte[] bytes = new byte[intsCRC.length];
        for (int i = 0; i < intsCRC.length; i++) {
            byte b1 = STool.intToByte(intsCRC[i]);
            bytes[i] = b1;
        }
        return bytes;
    }

    public static void deCodeCRC16() {

    }

}
